<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { UnpackQuery } from "@/services/unpacking";
import { isOpens } from "@/utils/directive.js";

// import { purchaseQuery, PurchaseCancel } from "@/services/delivery";

// import tabbarView from "../components/tabbar.vue";
const scrollTop = ref(0);
const topHeight = ref(uni.getStorageSync("topHight") || 0);
const code = ref("");
const listTabs = ref([
  { name: "全部", available: "" },
  { name: "任务生成", available: 0 },
  { name: "差异生成", available: 6 },
  { name: "盘点完成", available: 9 },
  { name: "已作废", available: 12 },
]);
const typeList = ref([
  { name: "全场盘点", id: 0 },
  { name: "单品盘点", id: 1 },
  { name: "分类盘点", id: 2 },
  { name: "品牌盘点", id: 3 },
]);

const ShopList = ref([]);

const changeTabs = (index) => {
  console.log(index);
  form.value.takeStatus = index.available;
  getappPlanQuery(1);
};

onLoad((option) => {
  code.value = option.code ? option.code : "";
  form.value.keyword = option.code ? option.code : "";

  // getAppSelectorAll();
});
onShow(() => {
  getappPlanQuery(1);
});
const getAppSelectorAll = async () => {
  let res = await appSelectorAll({ name: name.value });

  ShopList.value = res.data.datas;
};

const changeShop = (e) => {
  if (form.value.scId == e.id) {
    form.value.scId = "";
    return;
  }
  form.value.scId = e.id;
};

const changeType = (e) => {
  if (form.value.takeType === e.id) {
    form.value.takeType = "";
    return;
  }
  form.value.takeType = e.id;
};
const saveFun = () => {
  // console.log("取消");
  // form.value.name = "";
  // loading.value = "";
  // getappPlanQuery(1);
};

onReachBottom(() => {
  console.log("触底了");
  getappPlanQuery();
});

//获取商品
const form = ref({
  pageIndex: 1,
  pageSize: 20,
  createStartTime: "",
  createEndTime: "",
  scId: "",
  takeType: "",
  takeStatus: "",
  keyword: "",
});

const productData = ref([]);

const loading = ref("");
const getappPlanQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
    loading.value = "Loading";
  }
  if (index) {
    form.value.pageIndex = index;
  }
  if (loading.value == "noMore") {
    return;
  }
  loading.value = "Loading";
  try {
    let res = await UnpackQuery(form.value);
    if (res.code == 200) {
      productData.value = productData.value.concat(res.data.datas);
      console.log(productData.value);
      form.value.pageIndex = form.value.pageIndex + 1;

      if (res.data.datas.length < form.value.pageSize) {
        loading.value = "noMore";
      } else {
        loading.value = "More";
      }
    } else {
    }

    console.log(res);
  } catch (e) {}
};

//编辑商品
const goEdt = (item) => {
  if (
    isOpens(["manager:takeSheet:detail"]) ||
    isOpens(["shop:takeSheet:detail"])
  ) {
    uni.navigateTo({
      url: "/pages/stocktaking/p_det/index?id=" + item.id,
    });
  }
};
const ishowcamera = ref(false);
const scanFun = () => {
  console.log("扫码");
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=goods" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码

  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  form.value.keyword = res.result;
                  getappPlanQuery(1);
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      form.value.keyword = res.result;
      getappPlanQuery(1);
    },
  });
  // #endif
};
const searchFun = () => {
  console.log("搜索");
  uni.navigateTo({
    url: "/pages/goods/goods_search/index",
  });
};
const goadd = () => {
  uni.navigateTo({
    url: "/pages/stocktaking/add/index?type=add",
  });
};

const searchlistfun = () => {
  getappPlanQuery(1);
};
const clearlistfun = () => {
  getappPlanQuery(1);
};

const upper = (e) => {
  console.log(e);
};
const lower = (e) => {
  console.log(e);
};
const scroll = (e) => {
  console.log(e);
};
const sandfun = (item) => {
  uni.navigateTo({
    url: "/pages/delivery/send/index?id=" + item.id,
  });
};
const modalShow = ref(false);
const selectObj = ref({});
const titleShow = ref("");
const cancelFun = async (item) => {
  titleShow.value = "是否确认作废该盘点任务" + "?";
  selectObj.value = item;
  modalShow.value = true;
};
const modelConfirm = async () => {
  try {
    const res = await planCancel({ id: selectObj.value.id });
    if (res.code == 200) {
      modalShow.value = false;
      uni.showToast({
        title: "作废成功",
        icon: "none",
      });
      getappPlanQuery(1);
    }
  } catch (e) {
    uni.showToast({
      title: e.message,
      icon: "none",
    });
  }
};
const PDfun = (item) => {
  uni.navigateTo({
    url:
      "/pages/stocktaking/make/index?id=" +
      item.id +
      "&name=" +
      encodeURIComponent(item.name),
  });
};
const selectShow = ref(false);

const selectSearchDate = () => {
  selectShow.value = !selectShow.value;
};

function Time2(e) {
  const date = new Date(e);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(date.getDate()).padStart(2, "0");
  return `${year}-${month}-${day}`;
}

const createStartTimeShow = ref(false);
const createEndTimeShow = ref(false);
const dataOne = ref(Time2(new Date()));
const dataTwo = ref(Time2(new Date()));

const maxCountdata = ref(new Date().getTime());

const createStartTimefun = (e) => {
  dataOne.value = Time2(e.value);
  console.log(e.value, e.value > maxCountdata.value);
  if (e.value > maxCountdata.value) {
    maxCountdata.value = e.value;
    dataTwo.value = Time2(e.value);
  }

  createStartTimeShow.value = false;
};
const createEndTimefun = (e) => {
  dataTwo.value = Time2(e.value);
  // maxCountdata.value = e.value;
  createEndTimeShow.value = false;
};
const qxTime = () => {
  form.value.createStartTime = "";
  form.value.createEndTime = "";
  form.value.scId = "";
  form.value.takeType = "";
  form.value.keywords = "";
  getappPlanQuery(1);
  selectShow.value = false;
};

const selectdateTime = (e) => {
  form.value.createStartTime = dataOne.value + " 00:00:00";
  form.value.createEndTime = dataTwo.value + " 23:59:59";
  getappPlanQuery(1);
  selectShow.value = false;
};

const CYfun = (e) => {
  uni.navigateTo({
    url: "/pages/stocktaking/record_det/index?id=" + e.id,
  });
};
const QRfun = (e) => {
  uni.navigateTo({
    url: "/pages/stocktaking/record_det/index?id=" + e.id,
  });
};

//无网状态
const connected = () => {
  getappPlanQuery(1);
};
</script>

<template>
  <topNav
    title="拆包记录"
    @search="searchFun"
    @scan="scanFun"
    rType="save"
    :clickable="false"
  ></topNav>
  <!-- <view class="pay-top" :style="'top: calc( 88rpx + ' + topHeight + 'px);'">
    <view class="pay-search">
      <view class="pay-search-left">
        <up-search
          placeholder="商品名称/单据编号"
          v-model="form.keyword"
          @search="searchlistfun"
          @clear="clearlistfun"
          :showAction="false"
          shape="square"
        ></up-search>
      </view>
      <view
        class="pay-search-right"
        :class="selectShow ? 'pay-search-right2' : ''"
        @click="selectSearchDate"
      >
        <text>筛选</text>
        <up-icon
          class="play-right-fill"
          :class="selectShow ? 'rotate' : ''"
          name="play-right-fill"
          :color="selectShow ? '#1679fb' : '#c9cdd4'"
          size="24rpx"
        ></up-icon>
      </view>
    </view>
    <up-tabs
      :list="listTabs"
      @change="changeTabs"
      lineWidth="30rpx"
      lineColor="#1679FB"
      :activeStyle="{
        color: '#1679FB',
        fontWeight: '500',
        transform: 'scale(1.05)',
      }"
      :inactiveStyle="{
        color: '#4E5969',
        transform: 'scale(1)',
      }"
      itemStyle="padding-left: 0px; padding-right: 0px; height: 34px;"
    >
    </up-tabs>
  </view> -->

  <view class="goods_form">
    <!-- @click="goEdt(item)" -->
    <view class="scr_item" v-for="(item, index) in productData" :key="index">
      <view class="item_title" @click.stop>
        <up-copy :content="item.code">
          <view class="item_title_left">
            <text>拆包时间：{{ item.approveTime }}</text>
            <!-- <image
              style="margin-left: 8rpx"
              src="@/static/images/copy.png"
              mode="scaleToFill"
            /> -->
          </view>
        </up-copy>
        <text class="state">操作人: {{ item.createBy }}</text>
      </view>

      <view class="item_content">
        <view class="goods">
          <view class="goods-left">
            <view class="goods-left-img">
              <image :src="item.targetProductImage" mode="scaleToFill" />
            </view>
            <view class="goods-left-info">
              <view class="goods-left-info-title"
                ><text>{{ item.targetProductName }}</text></view
              >
              <view class="goods-left-info-code">{{
                item.targetProductBarCode || "--"
              }}</view>
            </view>
          </view>
          <view class="goods-right goods-right2">
            库存 +{{ item.targetNum }}
          </view>
        </view>
        <view class="goods goods2">
          <view class="goods-left">
            <view class="goods-left-img">
              <image :src="item.targetProductImage" mode="scaleToFill" />
            </view>
            <view class="goods-left-info">
              <view class="goods-left-info-title"
                ><text>{{ item.sourceProductName }}</text>
              </view>
              <view class="goods-left-info-code">{{
                item.sourceProductBarCode || "--"
              }}</view>
            </view>
          </view>
          <view class="goods-right goods-right1">
            库存 -{{ item.sourceNum }}
          </view>
        </view>
      </view>
    </view>
  </view>
  <view class="noData" v-if="productData.length <= 0 && loading == 'noMore'">
    <view class="noData-img">
      <image src="@/static/nodate/datas.png" mode="scaleToFill" />
      <view>暂无拆包记录~ </view>
    </view>
  </view>
  <view class="loading-form" v-if="loading && productData.length > 0"
    ><van-loading size="24rpx" v-if="loading == 'Loading'"
      ><text class="loading-text">加载中...</text>
    </van-loading>
    <text class="loading-text" v-if="loading == 'More'">加载更多</text>
    <text class="loading-text" v-if="loading == 'noMore'">~没有数据了~</text>
  </view>

  <!-- <view style="width: 100%; height: 100rpx"></view> -->

  <!-- <view class="goods_bt">
    <view class="goods_bt_to"
      ><up-button
        @click="goadd"
        type="primary"
        icon="plus"
        color="#1679FB"
        text="新增盘点任务"
      ></up-button>
    </view>
  </view> -->

  <up-popup
    :show="selectShow"
    mode="top"
    @close="selectShow = false"
    round="10"
    :closeOnClickOverlay="true"
    :safeAreaInsetBottom="true"
    :closeable="true"
  >
    <view
      class="pay-top"
      :style="'margin-top: calc( 88rpx + ' + topHeight + 'px);'"
    >
      <view class="pay-search">
        <view class="pay-search-left">
          <up-search
            placeholder="商品名称/单据编号"
            v-model="form.keyword"
            @search="searchlistfun"
            @clear="clearlistfun"
            :showAction="false"
            shape="square"
          ></up-search>
        </view>
        <view
          class="pay-search-right"
          :class="selectShow ? 'pay-search-right2' : ''"
          @click="selectSearchDate"
        >
          <text>筛选</text>
          <up-icon
            class="play-right-fill"
            :class="selectShow ? 'rotate' : ''"
            name="play-right-fill"
            :color="selectShow ? '#1679fb' : '#c9cdd4'"
            size="24rpx"
          ></up-icon>
        </view>
      </view>
    </view>
    <view class="popup-time">
      <view class="popup-time-title">筛选时间</view>
      <view class="popup-time-item">
        <view
          class="popup-time-item-title"
          :class="createStartTimeShow ? 'active' : ''"
          @click="createStartTimeShow = true"
          >{{ dataOne }}</view
        >
        <view class="popup-time-item-content">至</view>
        <view
          class="popup-time-item-title"
          :class="createEndTimeShow ? 'active' : ''"
          @click="createEndTimeShow = true"
          >{{ dataTwo }}</view
        >
      </view>
      <view class="popup-time-title">仓库</view>

      <view class="popup-time-item popup-time-item2">
        <scroll-view
          class="scroll-view_H"
          scroll-x="true"
          @scroll="scroll"
          scroll-left="0"
        >
          <view
            id="demo1"
            class="scroll-view-item_H uni-bg-red"
            :class="form.scId == item.id ? 'active' : ''"
            v-for="(item, index) in ShopList"
            :key="index"
            @click="changeShop(item)"
          >
            {{ item.name }}
          </view>
        </scroll-view>

        <!-- <view
          class="popup-time-item-title"
          @click="createStartTimeShow = true"
          >{{ dataOne }}</view
        >
        <view class="popup-time-item-content">-</view>
        <view
          class="popup-time-item-title"
          @click="createStartTimeShow = true"
          >{{ dataTwo }}</view
        > -->
      </view>
      <view class="popup-time-title">盘点类型</view>
      <view class="popup-time-item popup-time-item3">
        <view
          class="popup-time-item-stall"
          :class="form.takeType === item.id ? 'active' : ''"
          v-for="(item, index) in typeList"
          :key="index"
          @click="changeType(item)"
          >{{ item.name }}</view
        >
      </view>
      <view class="popup-bt-k">
        <up-button @click="qxTime" class="popup-qx" text="重置"></up-button>
        <up-button
          class="popup-bt"
          text="确定"
          @click="selectdateTime"
        ></up-button>
      </view>
    </view>
  </up-popup>
  <up-datetime-picker
    :show="createStartTimeShow"
    v-model="dataOne"
    @cancel="createStartTimeShow = false"
    @confirm="createStartTimefun"
    mode="date"
  ></up-datetime-picker>
  <up-datetime-picker
    :show="createEndTimeShow"
    :minDate="maxCountdata"
    v-model="dataTwo"
    @cancel="createEndTimeShow = false"
    @confirm="createEndTimefun"
    mode="date"
  ></up-datetime-picker>

  <up-modal
    :show="modalShow"
    :title="titleShow"
    :showCancelButton="true"
    cancelText="取消"
    confirmText="确定作废"
    confirmColor="#ff0101"
    width="540rpx"
    @cancel="modalShow = false"
    @confirm="modelConfirm"
  ></up-modal>
  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
